export interface Tabs {
	path: string
	label: string
}

import router from '@/router'
import { ElMessage } from 'element-plus'
import { defineStore } from 'pinia'
import { ref, reactive, watch } from 'vue'
import { useFullScreen } from '@/hooks/useFullScreen'

// 全局变量
const { toggleFull } = useFullScreen() // 全屏

export const useTabsStore = defineStore('tabs', () => {
	const tabs = reactive<Tabs[]>([{ path: '/analysis', label: '数据分析' }])

	const tabsName = ref(tabs[0].path)
	watch(tabsName, () => {
		router.push(tabsName.value)
	})

	const handleTabsAdd = (row: Tabs) => {
		const findIndex = tabs.findIndex((item: Tabs) => {
			return item.path === row.path
		})
		if (findIndex === -1) tabs.push(row)

		tabsName.value = row.path
	}

	const handleTabsDelete = (path: string) => {
		if (tabs.length <= 1) {
			ElMessage.info('至少保留一个选项卡')
			return
		}

		tabs.forEach((item, i) => {
			if (path === item.path) {
				tabs.splice(i, 1)
				// 删除后跳转前一个
				tabsName.value = tabs[tabs.length - 1].path
			}
		})
	}

	const handleReload = () => {
		router.replace(tabsName.value)
	}

	const handleFullScreen = () => {
		toggleFull(document.querySelector('.content') as HTMLElement, '#f0f2f5')
	}

	const handleCloseCurrent = () => {
		handleTabsDelete(tabsName.value)
	}

	const handleCloseOther = () => {
		const tab: Tabs | undefined = tabs.find((item: Tabs) => {
			return tabsName.value === item.path
		})

		if (tab) {
			tabs.splice(0, 9999999)
			tabs.push(tab)
		}
	}

	const handleCloseAll = () => {
		tabs.splice(0, 9999999)
		// 保留跳转默认
		tabs.push({ path: '/analysis', label: '数据分析' })
		tabsName.value = '/analysis'
	}

	return {
		tabs,
		tabsName,
		handleTabsAdd,
		handleTabsDelete,
		handleReload,
		handleFullScreen,
		handleCloseCurrent,
		handleCloseOther,
		handleCloseAll
	}
})
